{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## DFT TESTBENCH\n",
    "\n",
    "This notebook takes two inputs (real and imaginary) and gived the real and imaginary parts of the DFT outputs using AXI-STREAM. It is then compared with software version of FFT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pynq import Overlay\n",
    "import numpy as np\n",
    "from pynq import Xlnk\n",
    "from pynq.lib import dma\n",
    "from scipy.linalg import dft\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/local/lib/python3.6/dist-packages/pynq/pl_server/device.py:594: UserWarning: Users will not get PARAMETERS / REGISTERS information through TCL files. HWH file is recommended.\n",
      "  warnings.warn(message, UserWarning)\n"
     ]
    }
   ],
   "source": [
    "ol=Overlay('dft.bit')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/local/lib/python3.6/dist-packages/pynq/lib/dma.py:200: UserWarning: Failed to find parameter c_sg_length_width; users should really use *.hwh files for overlays.\n",
      "  warnings.warn(message, UserWarning)\n"
     ]
    }
   ],
   "source": [
    "dma1=ol.dft_block.dft_dma_1\n",
    "dma2=ol.dft_block.dft_dma_2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "NUM_SAMPLES = 1024\n",
    "\n",
    "real_error=np.zeros(NUM_SAMPLES)\n",
    "imag_error=np.zeros(NUM_SAMPLES)\n",
    "ind=np.arange(NUM_SAMPLES)\n",
    "real_rmse=np.zeros(NUM_SAMPLES)\n",
    "imag_rmse=np.zeros(NUM_SAMPLES)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "xlnk = Xlnk()\n",
    "in_r = xlnk.cma_array(shape=(NUM_SAMPLES,), dtype=np.float32) \n",
    "in_i = xlnk.cma_array(shape=(NUM_SAMPLES,), dtype=np.float32)           \n",
    "out_r = xlnk.cma_array(shape=(NUM_SAMPLES,), dtype=np.float32) \n",
    "out_i = xlnk.cma_array(shape=(NUM_SAMPLES,), dtype=np.float32)\n",
    "a = [i for i in range(NUM_SAMPLES)]\n",
    "a=np.cos(a)\n",
    "real=a.real                # Change input real and imaginary value here\n",
    "img=a.imag\n",
    "np.copyto(in_r, real)\n",
    "np.copyto(in_i, img)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "dft_ip = ol.dft_block.dft\n",
    "dft_ip.write(0x00,1)\n",
    "dma2.recvchannel.start()\n",
    "dma2.sendchannel.start()                # Start the DMA send and recv channels.\n",
    "dma1.recvchannel.start()\n",
    "dma1.sendchannel.start()\n",
    "\n",
    "dma2.recvchannel.transfer(out_i)        #Send and recv data \n",
    "dma2.sendchannel.transfer(in_i)\n",
    "dma1.recvchannel.transfer(out_r)\n",
    "dma1.sendchannel.transfer(in_r)\n",
    "\n",
    "dma2.recvchannel.wait()\n",
    "dma2.sendchannel.wait()                # Wait for the DMA to send and recv data.\n",
    "dma1.recvchannel.wait()\n",
    "dma1.sendchannel.wait()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Verifying Functionality "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "golden_op=np.fft.fft(a)\n",
    "\n",
    "for i in range(NUM_SAMPLES):\n",
    "\n",
    "    real_error[i]=\"{0:.6f}\".format(abs(out_r[i]-golden_op.real[i]))\n",
    "    imag_error[i]=\"{0:.6f}\".format(abs(out_i[i]-golden_op.imag[i]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sum_sq_real=0\n",
    "sum_sq_imag=0\n",
    "for i in range(NUM_SAMPLES):\n",
    "    sum_sq_real =sum_sq_real+(real_error[i]*real_error[i])\n",
    "    real_rmse = np.sqrt(sum_sq_real / (i+1))\n",
    "    sum_sq_imag =sum_sq_imag+(imag_error[i]*imag_error[i])\n",
    "    imag_rmse = np.sqrt(sum_sq_imag / (i+1))\n",
    "print(\"Real Part RMSE: \", real_rmse, \"Imaginary Part RMSE:\", imag_rmse)    \n",
    "if real_rmse<0.001 and imag_rmse<0.001:\n",
    "    print(\"PASS\")\n",
    "else:\n",
    "    print(\"FAIL\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Displaying Error and Output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(10, 5))\n",
    "plt.subplot(1,2,1)\n",
    "plt.bar(ind,real_error)\n",
    "plt.title(\"Real Part Error\")\n",
    "plt.xlabel(\"Index\")\n",
    "plt.ylabel(\"Error\")\n",
    "#plt.xticks(ind)\n",
    "plt.tight_layout()\n",
    "\n",
    "plt.subplot(1,2,2)\n",
    "plt.bar(ind,imag_error)\n",
    "plt.title(\"Imaginary Part Error\")\n",
    "plt.xlabel(\"Index\")\n",
    "plt.ylabel(\"Error\")\n",
    "#plt.xticks(ind)\n",
    "plt.tight_layout()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "freq=np.fft.fftfreq(1024)\n",
    "\n",
    "plt.figure(figsize=(7, 4))\n",
    "plt.subplot(1,2,1)\n",
    "plt.plot(freq,out_r,label='real')\n",
    "plt.plot(freq,out_i,label='imag')\n",
    "plt.title(\"1024-DFT\")\n",
    "plt.xlabel(\"Frequency\")\n",
    "plt.ylabel(\"DFT real and imaginary data\")\n",
    "plt.legend()\n",
    "plt.tight_layout()\n",
    "plt.subplot(1,2,2)\n",
    "plt.plot(freq,golden_op.real,label='real')\n",
    "plt.plot(freq,golden_op.imag,label='imag')\n",
    "plt.title(\"1024-FFT -Numpy\")\n",
    "plt.xlabel(\"Frequency\")\n",
    "plt.ylabel(\"FFT real and imaginary data\")\n",
    "plt.legend()\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
